package controller.admin;

import java.io.File;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.kit.FileKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import common.inter.AdminLoginInter;
import common.inter.CorsInter;
import common.kit.IpKits;
import common.kit.WebKit;
import controller.admin.base.BaseAdminController;
import model.Session;
import model.User;
import service.LoginService;
import service.UserRoleService;
import service.UserService;

@Clear
@Before(CorsInter.class)
public class AdminController extends BaseAdminController {
    @Inject
    private LoginService loginService;
    @Inject
    private UserService userService ;
    @Inject UserRoleService userToRoleService ;

    /**
     * 使用账号密码登录路由
     */
    public void login(){
        String username = getPara("username");
        String password = getPara("password");
        boolean keepLogin = getParaToBoolean("keepLogin", false);
        String loginIp = IpKits.getRealIp(getRequest());
        Ret ret = loginService.login(username, password, keepLogin, loginIp);
        renderJson(ret);
    }


    public void logout(){
        loginService.logout(getCookie(LoginService.cookieSessionIdName));
        removeCookie(LoginService.cookieSessionIdName);
        renderJson(Ret.ok());
    }
    
    public void captcha() {
		renderCaptcha();
	}

    @Before({AdminLoginInter.class})
    public void home() {
    	User user = getLoginUser();
    	set("user", user);
        render("home.html");
    }
    
    public void checkSession() {
    	String token = getPara("token");
    	Session session = Session.dao.findById(token);
    	renderJson( null == session ? Ret.fail() : Ret.ok() );
	}
    
    @Before(AdminLoginInter.class)
    public void globalData() {
		User loginUser = getLoginUser() ;
		set("admin", loginUser);
		set("menuList", userToRoleService.findUserToMenu(loginUser));
		renderJson();
	}
    
    @Before(AdminLoginInter.class)
    public void uploadPic() {
		String route = "/uploadPic" ;
		UploadFile file = getFile("upfile" , route );
		String extension = FileKit.getFileExtension(file.getFile());
		String newName =  StrKit.getRandomUUID() + "." + extension ;
		String newPath = file.getUploadPath() + File.separator + newName ;
		file.getFile().renameTo(new File(newPath));
		String localPath = WebKit.getCtx(getRequest()) + "/upload/uploadPic/" + newName ;
		renderJson("url" , localPath);
	}
    
}
